<template>
  <el-dialog 
    v-model="dialogVisible" 
    :title="isPositionSpecified ? `添加章节（在第${insertPosition}章之后）` : '添加章节'" 
    width="600px"
    @close="handleClose">
    <el-form :model="chaptersForm" ref="chaptersFormRef">
      <div v-if="!isPositionSpecified" class="position-selector">
        <el-form-item label="添加位置" required>
          <el-radio-group v-model="addPosition">
            <el-radio :label="'beginning'">开头添加</el-radio>
            <el-radio :label="'end'">末尾添加</el-radio>
            <el-radio :label="'specific'">指定位置</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="addPosition === 'specific'" label="在第几章后">
          <el-input-number v-model="insertPosition" :min="1" :max="maxPosition" />
        </el-form-item>
      </div>
      
      <el-form-item
        v-for="(item, idx) in chaptersForm.chapters"
        :key="idx"
        :label="'章节' + (idx + 1)"
        :prop="'chapters.' + idx + '.chapterName'"
        :rules="[{ required: true, message: '请输入章节名称', trigger: 'blur' }]"
      >
        <div style="display: flex; align-items: center; gap: 10px; width: 100%;">
          <el-input v-model="item.chapterName" placeholder="章节名称" style="width: 250px;" />
          <el-input v-model.number="item.chapterOrder" type="number" min="1" placeholder="顺序" style="width: 80px;" />
          <el-button 
            type="danger" 
            :icon="Delete" 
            @click="removeChapter(idx)" 
            v-if="chaptersForm.chapters.length > 1" 
            circle 
          />
        </div>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="addChapterRow">添加一行</el-button>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitChapters">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  courseId: {
    type: [String, Number],
    required: true
  },
  existingChapters: {
    type: Array,
    default: () => []
  },
  insertAt: {
    type: Number,
    default: -1
  }
})

const emit = defineEmits(['update:visible', 'submit'])

// 组件内部状态
const dialogVisible = ref(false)
const chaptersFormRef = ref(null)
const chaptersForm = reactive({ 
  chapters: [{ chapterName: '', chapterOrder: 1 }] 
})
const isPositionSpecified = ref(false)
const addPosition = ref('end')
const insertPosition = ref(1)

// 监听外部visible变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  
  if (newVal) {
    initializeForm()
  }
})

// 监听内部dialogVisible变化
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 计算属性 - 最大插入位置
const maxPosition = ref(1)

// 初始化表单
const initializeForm = () => {
  // 更新最大插入位置
  maxPosition.value = props.existingChapters.length
  
  // 检查是否指定了插入位置
  if (props.insertAt > 0) {
    isPositionSpecified.value = true
    insertPosition.value = props.insertAt
    
    // 计算合适的章节顺序
    const targetOrder = props.insertAt < props.existingChapters.length 
      ? (props.existingChapters[props.insertAt-1].chapterOrder + props.existingChapters[props.insertAt].chapterOrder) / 2
      : props.existingChapters[props.insertAt-1].chapterOrder + 1
      
    chaptersForm.chapters = [{ 
      chapterName: '', 
      chapterOrder: Math.floor(targetOrder)
    }]
  } else {
    isPositionSpecified.value = false
    addPosition.value = 'end'
    
    const startOrder = props.existingChapters.length > 0 
      ? props.existingChapters[props.existingChapters.length - 1].chapterOrder + 1 
      : 1
      
    chaptersForm.chapters = [{ 
      chapterName: '', 
      chapterOrder: startOrder 
    }]
  }
}

// 添加章节行
const addChapterRow = () => {
  const lastOrder = chaptersForm.chapters[chaptersForm.chapters.length - 1].chapterOrder
  chaptersForm.chapters.push({ 
    chapterName: '', 
    chapterOrder: lastOrder + 1
  })
}

// 删除章节行
const removeChapter = (idx) => {
  chaptersForm.chapters.splice(idx, 1)
}

// 关闭对话框
const handleClose = () => {
  chaptersForm.chapters = [{ chapterName: '', chapterOrder: 1 }]
}

// 提交章节
const submitChapters = async () => {
  if (!chaptersForm.chapters.length) return
  
  if (chaptersFormRef.value) {
    try {
      await chaptersFormRef.value.validate()
      
      // 根据位置调整章节顺序
      if (!isPositionSpecified.value && addPosition.value !== 'end') {
        if (addPosition.value === 'beginning') {
          const minOrder = props.existingChapters.length > 0 
            ? Math.min(...props.existingChapters.map(c => c.chapterOrder)) - 1 
            : 1
          
          chaptersForm.chapters.forEach((c, idx) => {
            c.chapterOrder = minOrder + idx
          })
        } else if (addPosition.value === 'specific' && insertPosition.value > 0) {
          if (insertPosition.value <= props.existingChapters.length) {
            const prevOrder = props.existingChapters[insertPosition.value - 1].chapterOrder
            const nextOrder = insertPosition.value < props.existingChapters.length 
              ? props.existingChapters[insertPosition.value].chapterOrder 
              : prevOrder + chaptersForm.chapters.length + 1
              
            const step = (nextOrder - prevOrder) / (chaptersForm.chapters.length + 1)
            
            chaptersForm.chapters.forEach((c, idx) => {
              c.chapterOrder = Math.floor(prevOrder + step * (idx + 1))
            })
          }
        }
      }
      
      // 检查是否有空章节名称
      const invalidChapters = chaptersForm.chapters.filter(c => !c.chapterName || c.chapterName.trim() === '')
      if (invalidChapters.length > 0) {
        ElMessage.warning('请填写所有章节名称')
        return
      }
      
      // 生成要提交的数据
      const chaptersToSubmit = chaptersForm.chapters.map(chapter => ({
        chapterId: chapter.chapterId || 0,
        chapterName: chapter.chapterName,
        chapterOrder: chapter.chapterOrder
      }))
      
      // 发送数据到父组件
      emit('submit', chaptersToSubmit)
      
      // 重置表单
      chaptersForm.chapters = [{ chapterName: '', chapterOrder: 1 }]
      
    } catch (e) {
      console.error('验证失败:', e)
    }
  }
}

// 初始化
watch(() => props.existingChapters, () => {
  if (dialogVisible.value) {
    initializeForm()
  }
}, { immediate: true })
</script>

<style scoped>
.position-selector {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #ebeef5;
}
</style> 